package com.guyan.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guyan.entity.User;
import com.guyan.mapper.UserMapper;
import com.guyan.service.UserService;
import com.guyan.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * ClassName： UserServiceImpl
 * Date： 2021/6/11 13:59
 *
 * @author 孤焰
 * @version 1.0
 **/

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResultVo login(String username, String password) {
        User user = userMapper.getUserByUsername(username);
        if (user == null) {
            return ResultVo.error(6000, "不存在该用户");
        }
        if (!password.equals(user.getPassword())) {
            return ResultVo.error(6000, "密码错误");
        }

        return ResultVo.success(user);
    }

    @Override
    public PageInfo userList(Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        PageInfo pageInfo = new PageInfo(userMapper.userList());
        return pageInfo;
    }

    @Override
    public ResultVo addUser(User user) {
        User userDb = userMapper.getUserByUsername(user.getUsername());

        if (userDb != null) {
            return ResultVo.error(6000, "已存在该用户，创建失败");
        }

        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        return userMapper.addUser(user) > 0 ?
                ResultVo.success() : ResultVo.error(6000, user+"数据库层异常，用户创建失败");
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public ResultVo updateUserById(User user) {
        User userDb = userMapper.getUserByUsername(user.getUsername());

        if (userDb == null) {
            return ResultVo.error(6000, "不存在该用户，更新失败");
        }

        user.setUpdateTime(new Date());

        return userMapper.updateUserById(user) > 0 ?
                ResultVo.success() : ResultVo.error(6000, user+"数据库层异常，用户更新失败");
    }

    @Override
    public ResultVo batchDelUser(Integer[] ids) {
        return userMapper.batchDelUser(ids) > 0 ?
                ResultVo.success() : ResultVo.error(6000, "用户信息批量删除出错");
    }
}
